﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using TeacherHelp.DAL;
using TeacherHelp.Util;
using TeacherHelp.ViewModel;

namespace TeacherHelp.BLL
{
    public class UserManager
    {
        private readonly UserService _userService;
        private readonly TeacherLinkGradeService _teacherLinkGrade;

        public UserManager()
        {
            _userService = new DAL.UserService();
            _teacherLinkGrade = new DAL.TeacherLinkGradeService();
        }
        public List<ViewModel.User> GetUserAllList()
        {
            string sql = _userService.GetUserInfoSQL();
            try
            {
                Log.Info("获取User集合..");
                return DBHelper.GetListModel<ViewModel.User>(sql);
            }
            catch (Exception ex)
            {
                Log.Error("获取User集合出现异常!", ex);
                return default;
            }
        }

        public List<ViewModel.User> GetUserByUserName(string userName)
        {
            string sql = _userService.GetUserInfoByUserNameSQL(userName);
            try
            {
                Log.Info("根据userName获取User集合.. userName=" + userName);
                return DBHelper.GetListModel<ViewModel.User>(sql);
            }
            catch (Exception ex)
            {
                Log.Error("获取User集合出现异常! userName=" + userName, ex);
                return default;
            }
        }

        public ViewModel.User GetUserByUserId(int userId)
        {
            string sql = _userService.GetUserInfoByUserIdSQL(userId);
            try
            {
                Log.Info("根据userId获取User对象.. userId=" + userId);
                return DBHelper.GetOneModel<ViewModel.User>(sql);
            }
            catch (Exception ex)
            {
                Log.Error("获取User集合出现异常! userId=" + userId, ex);
                return default;
            }
        }

        public string AddUser(ViewModel.User newUser)
        {
            string msg = "添加用户失败！";
            Log.Info("添加用户中..");

            string existsSql = _userService.GetUserExistsSQL(newUser.LoginName);

            if (DBHelper.ExecuteScalar(existsSql).ToInt() > 0)
            {
                msg = "用户名已存在！";
                Log.Info(msg);
                return msg;
            }

            Model.User user = new Model.User
            {
                Id = newUser.Id,
                Name = newUser.Name,
                LoginName = newUser.LoginName,
                LoginPwd = MD5Helper.encrypt(newUser.LoginPwd),
                RoleId = newUser.RoleId,
                Sex = newUser.Sex
            };
            //学生所属班级  老师管理的班级
            if (newUser.RoleId != 1 && newUser.roleName != "管理员")
            {
                var userSql = SQLBuilder.GetInsertSQLByModel(user) + SQLBuilder.GetIdentity();
                object executResult = null;
                try
                {
                    executResult = DBHelper.ExecuteScalar(userSql);
                }
                catch (Exception ex)
                {
                    Log.Error("添加用户时出现异常!", ex);
                }
                if (executResult == null)
                {
                    msg = "添加用户时失败！";
                    Log.Info(msg + "\nuserSql:" + userSql + "\n返回结果(executResult)：" + executResult);
                }
                else
                {
                    Model.TeacherLinkGrade teacherLinkGrade = new Model.TeacherLinkGrade
                    {
                        GradeId = newUser.gradeId,
                        UserId = executResult.ToInt()
                    };
                    var gradeSql = SQLBuilder.GetInsertSQLByModel(teacherLinkGrade);
                    int rows = 0;
                    try
                    {
                        rows = DBHelper.ExecuteNonQuery(gradeSql);
                    }
                    catch (Exception ex)
                    {
                        Log.Error("添加用户和班级之间的关系出现异常！", ex);
                    }

                    if (rows > 0)
                    {
                        msg = "保存成功！";
                        Log.Info("添加用户成功！roleName=" + newUser.roleName);
                    }
                    else
                    {
                        msg = "保存失败！";
                        Log.Info(msg + "\ngradeSql:" + gradeSql + "\n返回结果(rows)：" + rows);
                    }
                }
            }
            else
            {
                var userSql = SQLBuilder.GetInsertSQLByModel(user);
                var executResult = DBHelper.ExecuteNonQuery(userSql);
                if (executResult > 0)
                {
                    msg = "保存成功！";
                    Log.Info("添加用户成功！roleName=" + newUser.roleName);
                }
                else
                {
                    msg = "保存失败！";
                    Log.Info(msg + "\nuserSql:" + userSql + "\n返回结果(executResult)：" + executResult);
                }
            }
            return msg;

        }

        public string RemoveUser(int userId)
        {
            string msg = "删除用户失败！";
            Log.Info("删除用户中..");
            string sql = _userService.DeleteUserByIdSQL(userId) + ";\n";
            sql += _teacherLinkGrade.DeleteTeacherLinkGradeByUserIdSQL(userId) + ";\n";
            int executResult = DBHelper.ExecuteNonQuery(sql);
            if (executResult > 0)
            {
                msg = "删除成功！";
                Log.Info("删除用户成功！userId=" + userId);
            }
            else
            {
                msg = "删除失败！";
                Log.Info(msg + "\n userId=" + userId + "\nsql:" + sql + "\n返回结果(executResult)：" + executResult);
            }
            return msg;

        }

        public string EditUser(ViewModel.User newUser)
        {
            string msg = "修改用户失败！";
            Log.Info("修改用户中..");
            Model.User user = new Model.User
            {
                Name = newUser.Name,
                LoginName = newUser.LoginName,
                LoginPwd = MD5Helper.encrypt(newUser.LoginPwd),
                RoleId = newUser.RoleId,
                Sex = newUser.Sex
            };

            Model.TeacherLinkGrade teacherLinkGrade = new Model.TeacherLinkGrade
            {
                GradeId = newUser.gradeId
            };

            string sql = SQLBuilder.GetUpdateSQLByModel(user) + _userService.GetIdWhereSQL(newUser.Id) + ";\n";

            string isExistsTeacherLinkGradeSQL = _teacherLinkGrade.GetCountSQL() + _userService.GetUserIdWhereSQL(newUser.Id) + ";";
            object execResult = null;
            try
            {
                execResult = DBHelper.ExecuteScalar(isExistsTeacherLinkGradeSQL);
            }
            catch (Exception ex)
            {
                Log.Error("查询用户和班级的关系时出现异常！", ex);
            }

            if (execResult.ToInt() == 0)
            {
                //如果不存在就添加
                teacherLinkGrade.UserId = newUser.Id;
                sql += SQLBuilder.GetInsertSQLByModel(teacherLinkGrade);
            }
            else
            {
                //如果存在就修改
                sql += SQLBuilder.GetUpdateSQLByModel(teacherLinkGrade) + _userService.GetUserIdWhereSQL(newUser.Id) + ";";
            }

            int rows = 0;

            try
            {
                rows = DBHelper.ExecuteNonQuery(sql);
            }
            catch (Exception ex)
            {
                Log.Error("修改用户时出现异常！", ex);
            }
            if (rows > 0)
            {
                msg = "修改成功！";
            }
            else
            {
                msg = "修改失败！";
            }
            Log.Info(msg);
            return msg;

        }
    }
}